#!/bin/bash

if [ -z $RUNNER ]; then
    # docker or podman
    RUNNER="docker"
fi

echo "RUNNER: ${RUNNER}"

GIT_ROOT=$(git rev-parse --show-toplevel)

VERSION=${1:-$(yq -r .Version ${GIT_ROOT}/configuration/build_config.yaml)}
CONTAINER_NAME=$(yq -r '.["Base-Name"]' ${GIT_ROOT}/configuration/build_config.yaml)
REPO_NAME=$(yq -r .Repository ${GIT_ROOT}/configuration/build_config.yaml)

echo "Exporting dev container ${VERSION}"

NAME="container_export"

echo "Stopping and deleting the container ${NAME}..."
$RUNNER stop $NAME 2>&1 1>/dev/null | true
$RUNNER rm $NAME 2>&1 1>/dev/null | true

echo "Exporting the container ${NAME}..."

set -e

$RUNNER run --name "${NAME}" "${REPO_NAME}/${CONTAINER_NAME}:${VERSION}"
$RUNNER export "${NAME}" | xz -T0 >"${CONTAINER_NAME}_${VERSION}.tar.xz"
$RUNNER stop "${NAME}"
$RUNNER rm "${NAME}"
